<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"> 
    <title>object reference</title>
</head>

<body>


<script>
// 复制
var a = 5;
var b = a;
b += 3;
console.log(a, b);  // 5 8


// 对象和函数都是引用的关系
var a = [1,2,3];
var b = a;
b.push(4);
console.log(a, b);  //[1, 2, 3, 4] [1, 2, 3, 4] 


var a = [1,2,3];
var b = a;
b = [1,2,3,4];
console.log(a, b);  //[1, 2, 3] [1, 2, 3, 4]


var obj = {
	a: 10
}
var obj2 = obj;
obj2.a = 20;
console.log(obj, obj2); //Object {a: 20} Object {a: 20} 


// 如何拷贝一个对象？
//浅拷贝
function copy(obj){  
	var newObj = {};
	for(var attr in obj){
		newObj[attr] = obj[attr];
	}
	return newObj;
}

var obj = {a: 10}
var obj2 = copy(obj);
obj2.a = 20;
console.log(obj, obj2); //Object {a: 10} Object {a: 20} 


// 浅拷贝的问题--只拷贝对象一层
// obj[a] 指向{b:10} 对象； 
// 执行newObj[a] = obj[a]，newObj[a]指向同一个对象，是一个引用的关系
var obj = {a: {b: 10}}
var obj2 = copy(obj);
obj2.a.b = 20;
console.log(obj, obj2); //Object {a: {b: 20}} Object {a: {b: 20}} 



// 深拷贝
function deepCopy(obj){
	if(typeof obj!= 'object'){
		return obj;
	}
	var newObj = {};
	for(var attr in obj){
		newObj[attr] = deepCopy(obj[attr]);
	}
	return newObj;
}

var obj = {a: {b: 10}}
var obj2 = deepCopy(obj);
obj2.a.b = 20;
console.log(obj, obj2); //Object {a: {b: 10}} Object {a: {b: 20}

</script>

</body>
</html>